package cn.tedu.tea.controller;

import cn.tedu.tea.assemble.ContentAssemble;
import cn.tedu.tea.domain.param.ContentParam;
import cn.tedu.tea.domain.param.ContentUpParam;
import cn.tedu.tea.domain.vo.ContentVO;
import cn.tedu.tea.domain.vo.FileVO;
import cn.tedu.tea.ex.ServiceException;
import cn.tedu.tea.service.IContentService;
import cn.tedu.tea.util.FileUtil;
import cn.tedu.tea.web.R;
import cn.tedu.tea.web.ServiceCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
* @author Hyanze
* @description 内容控制层
* @date 2023/4/21 2023/4/21
*/
@Slf4j
@Api(tags = "内容相关接口")
@RestController
@RequestMapping("/content")
@CrossOrigin
public class ContentController {

    @Autowired
    private IContentService iContentService;

    @Value("${baking.image.imagePath}")
    private String imagePath;

    @Value("${baking.image.url}")
    private String url;

    @GetMapping("/list")
    @ApiOperation("内容列表")
    public R<List<ContentVO>> list(){
        return R.ok(ContentAssemble.ContentListBO2VO(iContentService.list()));
    }

    @GetMapping("/{id}")
    @ApiOperation("内容详情")
    public R<ContentVO> getById(@PathVariable("id")Integer id){
        return R.ok(ContentAssemble.ContentBO2VO(iContentService.getById(id)));
    }

    @PostMapping("/add")
    @ApiOperation("新增内容")
    public R<Void> add(@RequestBody ContentParam contentDTO){
        iContentService.add(contentDTO);
        return R.ok();
    }

    @PostMapping("/up")
    @ApiOperation("更新内容")
    public R<Void> update(@RequestBody ContentUpParam contentUpDTO){
        iContentService.update(contentUpDTO);
        return R.ok();
    }

    @PostMapping("/del/{id}")
    @ApiOperation("删除内容")
    public R<Void> deleteById(@PathVariable("id") Integer id){
        iContentService.deleteById(id);
        return R.ok();
    }

    @PostMapping("/fileUpload")
    @ApiOperation("文件上传")
    public FileVO fileUpload(MultipartFile file){
        FileVO fileVO = new FileVO();
        // 文件名
        String fileName = "";
        // 图片URL路径
        String urlPath = "";
        try {
            //上传图片
            fileName = FileUtil.makeTempFile(file, imagePath);
//            log.debug("上传成功,fileName={}",fileName);
            urlPath = url + fileName;
        } catch (Exception e) {
            throw new ServiceException(ServiceCode.ERR_FILE_UPLOAD);
        }
        fileVO.setUrl(urlPath);
        fileVO.setFileName(file.getOriginalFilename());
        fileVO.setSysFileName(fileName);
        fileVO.setType(FileUtil.getFileExtension(file));
        return fileVO;
    }
}
